package cn.wolfcode.java39.api._02_producer_type;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;

import java.util.concurrent.CountDownLatch;

public class AyncProducer {
    public static void main(String[] args) throws Exception {
        //实例化消息生产者Producer
        DefaultMQProducer producer = new DefaultMQProducer("wolfcode-producer");
        //设置NameServer的地址
        producer.setNamesrvAddr("192.168.174.101:9876;192.168.174.102:9876");
        //启动Producer实例
        producer.start();
        //创建一个计数器
        CountDownLatch count = new CountDownLatch(100);
        //创建message的对象
        for (int i = 0; i < 100; i++) {
            //创建消息,并指定Topic,Tag和消息体
            Message msg = new Message("02-producer-type" , "TagA" , ("Hello RocketMQ " + i).getBytes("utf-8") );
            //发送异步消息到一个Broker
            producer.send(msg, new SendCallback() {
                public void onSuccess(SendResult sendResult) {
                    System.out.println("消息发送成功");
                    //计数器减一
                    count.countDown();
                }

                public void onException(Throwable throwable) {
                    System.out.println("消息发送失败");
                    //计数器减一
                    count.countDown();
                }
            });
        }
        //让线程阻塞,当所有的回调执行完成之后,才去执行下面的代码
        count.await();//等待计数器的值变为0
        // 如果不再发送消息，关闭Producer实例。
        producer.shutdown();
    }
}
